using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TransformationGrid : MonoBehaviour
{
    public Transform prefab;
    public int gridResolution = 10;
    Transform[] grid;

    // Start is called before the first frame update
    void Start()
    {
        
    }
    void Test1() {
        grid = new Transform[gridResolution * gridResolution * gridResolution];
        for (int i = 0, z = 0; z < gridResolution; z++)
        {
            for (int y = 0; y < gridResolution; y++)
            {
                for (int x = 0; x < gridResolution; x++,i++)
                {
                    grid[i] = CreateGridPoint(x, y, z);
                }
            }
        }
    }
    Transform CreateGridPoint(int x, int y, int z) {
        Transform point = Instantiate<Transform>(prefab);
        point.localPosition = GetCoordinates(x,y,z);
         point.GetComponent<MeshRenderer>().material.color = new Color((float)x / gridResolution, (float)y / gridResolution,(float)z / gridResolution);

        return point;
    }
    Vector3 GetCoordinates(int x, int y, int z) {
        return new Vector3(
          x - (gridResolution - 1) * 0.5f,
          y - (gridResolution - 1) * 0.5f,
          z - (gridResolution - 1) * 0.5f
          );
    }

   Transformation[] transformations;
    private void Awake()
    {
        Test1();
        Test2();
    }
    void Test2() {
        transformations = new Transformation[gridResolution * gridResolution * gridResolution];
        for (int i = 0; i < transformations.Length; i++)
        {
            transformations[i] = grid[i].transform.GetComponent<Transformation>();
        }
    }
    Vector3 TransformPoint(int x,int y,int z) {
        Vector3 coordinates = GetCoordinates(x,y,z);
        for (int i = 0; i < transformations.Length; i++)
        {
            coordinates = transformations[i].Apply(coordinates);
        }
        return coordinates;
    }
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space)) {
            for (int i = 0, z = 0; z < gridResolution; z++)
            {
                for (int y = 0; y < gridResolution; y++)
                {
                    for (int x = 0; x < gridResolution; x++, i++)
                    {
                        grid[i].localPosition = TransformPoint(x, y, z);
                    }
                }
            }
        }
      
    }
}
